import { GameConst } from "../constant/GameConst";
import Core from "../Core";
import AutoBindComponent from "./AudioBindComponent";

const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu("通用组件/MyComponent")
export default class MyComponent<T = any> extends AutoBindComponent {
  layer: GameConst.WIN_LAYER;
  winType: GameConst.WIN_TYPE;
  data: T | null = null;
  closeCallback: (() => void) | null = null;

  show(data: any = null) {
    this.data = data;
  }

  protected onDestroy() {
    this.unscheduleAllCallbacks();
    this.node.targetOff(this); // 解绑所有事件
    cc.Tween.stopAllByTarget(this.node);
    this["closecb"] = null;
  }

  protected showEnable(): void {}

  protected beforeDisable(): void {}

  protected onEnable(): void {
    this.initEvent();
    this.showEnable();
  }

  protected onDisable(): void {
    this.removeEvent();
    this.beforeDisable();
  }

  protected initEvent() {
    //todo
  }

  protected removeEvent() {
    //todo
  }

  close() {
    // 调用 WindowManager 的关闭
    Core.windowManager.removeWin(this.node.name);
  }

  // 根据按钮名生成对应的处理函数名
  protected getHandlerMethodName(name: string): keyof this | null {
    if (!name.startsWith("btn_")) return null;
    // btn_user → onClickBtnUser
    // btn_portal → onClickBtnPortal
    // btn_test_win -> onClickBtnTestWin
    const suffix = name.split("_").slice(1); // 去掉 btn_
    const capitalized = suffix
      .map((s) => s.charAt(0).toUpperCase() + s.slice(1))
      .join("");
    return `onClickBtn${capitalized}` as keyof this;
  }

  protected onBtnClick(event) {
    Core.audioManager.playButtonClicked();
    const targetName = event.target.name;
    // 自动生成方法名：onClickBtnUser → "onClick" + "User"
    const handlerName = this.getHandlerMethodName(targetName);
    console.log("onBtnClick: " + handlerName.toString());
    if (handlerName && typeof this[handlerName] === "function") {
      this[handlerName](); // 动态调用方法
    }
  }

  getNode(key: string): cc.Node {
    if (this[key].node) {
      return this[key].node;
    }
    return this[key];
  }

  getLabel(key: string): cc.Label {
    return this[key];
  }

  getButton(key: string): cc.Button {
    return this[key];
  }

  getSprite(key: string): cc.Sprite {
    return this[key];
  }

  getEditBox(key: string): cc.EditBox {
    return this[key];
  }

  getRichLabel(key: string): cc.RichText {
    return this[key];
  }

  getSkeleton(key: string): sp.Skeleton {
    return this[key];
  }

  onClickBtnClose() {
    this.close();
  }
}
